package com.block.common.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.SourceCountDTO;
import com.block.common.mq.MqSourceCountSendService;
import com.block.common.service.ISourceBaseInfoService;
import com.block.common.service.ISourceDataCallbackLogService;
import com.block.common.service.ISourceDataCountInfoService;
import com.block.common.service.LogFactory;
import com.block.db.entity.SourceBaseInfo;
import com.block.db.entity.SourceDataCallbackLog;
import com.block.db.entity.SourcePushResultInfo;
import com.block.db.mapper.SourceDataCallbackLogMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 线索回调日志 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-12-28
 */
@Service
public class SourceDataCallbackLogServiceImpl extends ServiceImpl<SourceDataCallbackLogMapper, SourceDataCallbackLog> implements ISourceDataCallbackLogService {

    private static final Logger log = LogFactory.getSourceLog();

    @Autowired
    ISourceBaseInfoService sourceBaseInfoService;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    MqSourceCountSendService mqSourceCountSendService;
    @Autowired
    ISourceDataCountInfoService sourceDataCountInfoService;


    @Override
    @Transactional
    public boolean resultToCallBack(SourcePushResultInfo pushResultInfo) {

        boolean noticeFlag = false;
        try {

//            SourceCountDTO sourceCountDTO = new SourceCountDTO(pushResultInfo.getChannelCode(), pushResultInfo.getChannelName());
//            sourceCountDTO.setNoticeNumber(1);
//            sourceDataCountInfoService.saveSourceCountInfo(sourceCountDTO);

            SourceBaseInfo sourceBaseInfo = sourceBaseInfoService.getSourceBaseInfoByCode(pushResultInfo.getChannelCode());

            if (StrUtil.isEmpty(sourceBaseInfo.getCallbackUrl())){
                throw new RuntimeException(StrUtil.format("回调地址为空【channelCode】{}【channelName】{}", sourceBaseInfo.getChannelCode(), sourceBaseInfo.getChannelName()));
            }

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("resultNo", String.valueOf(pushResultInfo.getId()));

            SourceDataCallbackLog callbackLog = this.initCallBackLog(pushResultInfo, paramMap);

            String result = this.callbackHttp(paramMap, sourceBaseInfo);

            JSONObject resultObject = JSON.parseObject(result);
            String code = resultObject.getString("code");

            SourceDataCallbackLog updateEntity = new SourceDataCallbackLog();
            updateEntity.setId(callbackLog.getId());
            updateEntity.setRequestUrl(sourceBaseInfo.getCallbackUrl());
            updateEntity.setResultInfo(result);
            if (StrUtil.equals("200", code)){
                updateEntity.setStatus("SUCCESS");

//                sourceCountDTO.setNoticeNumber(null);
//                sourceCountDTO.setNoticeSuccessNumber(1);
////                mqSourceCountSendService.sourceDataCountSend(sourceCountDTO);
//                sourceDataCountInfoService.saveSourceCountInfo(sourceCountDTO);

                noticeFlag = true;
            }else{
                updateEntity.setStatus("FAILED");
            }
            this.updateById(updateEntity);
            return noticeFlag;
        }catch (Exception exception){
            exception.printStackTrace();
            String message = StrUtil.format("【channelCode】{}【channelName】{}", pushResultInfo.getChannelCode(), pushResultInfo.getChannelName());
            notifyExceptionService.notifyNoticeInfo("SOURCE_PUSH_NOTICE_LOG", "线索推送回调请求", message, exception);
        }
        return noticeFlag;
    }

    public SourceDataCallbackLog initCallBackLog(SourcePushResultInfo pushResultInfo, Map<String, Object> paramMap){
        SourceDataCallbackLog callbackLog = new SourceDataCallbackLog();
        callbackLog.setDateInfo(LocalDate.now().toString());
        callbackLog.setChannelCode(pushResultInfo.getChannelCode());
        callbackLog.setChannelName(pushResultInfo.getChannelName());
        callbackLog.setDataId(String.valueOf(pushResultInfo.getDataId()));
        callbackLog.setResultNo(String.valueOf(pushResultInfo.getId()));
        callbackLog.setParamInfo(JSON.toJSONString(paramMap));
        callbackLog.setStatus("INIT");

        this.save(callbackLog);

        return this.getById(callbackLog.getId());
    }


    public String callbackHttp(Map<String, Object> paramMap, SourceBaseInfo sourceBaseInfo){

        String callbackUrl = sourceBaseInfo.getCallbackUrl();

        log.info("【线索回调】开始【channelCode】{}【channelName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                sourceBaseInfo.getChannelCode(), sourceBaseInfo.getChannelName(), callbackUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(callbackUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【线索回调】结束【channelCode】{}【channelName】{}【result】{}", sourceBaseInfo.getChannelCode(), sourceBaseInfo.getChannelName(), result);

        return result;
    }

}
